<template>
  <div class="history-container">
    <!-- 顶部导航栏 -->
    <el-header class="app-header">
      <div class="logo">
        <img src="@/assets/logo.png" alt="Logo" class="logo-image">
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
      <el-card shadow="never" class="history-card">
        <template #header>
          <div class="section-header">
            <el-icon :size="18" color="#4caf50"><Clock /></el-icon>
            <span class="section-title">历史记录</span>
            <el-button type="text" @click="goBack" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
          </div>
        </template>

        <el-table
            :data="historyRecords"
            style="width: 100%"
            v-loading="loading"
            element-loading-text="加载中..."
            element-loading-background="rgba(255, 255, 255, 0.8)"
            empty-text="暂无历史记录"
            @row-click="showDetails"
        >
          <el-table-column prop="detection_id" label="识别ID" width="120" />
          <el-table-column prop="detection_time" label="识别时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.detection_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="feature_name" label="识别类型">
            <template #default="{row}">
              <el-tag :type="getTagType(row.feature_id)">
                {{ row.feature_name }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="showDetailModal"
        title="识别详情"
        width="90%"
        :fullscreen="$isMobile()"
        custom-class="detail-dialog"
    >
      <div class="result-content" v-if="selectedRecord">
        <div class="main-section">
          <!-- 图片区域 -->
          <el-card shadow="never" class="image-card">
            <template #header>
              <div class="section-header">
                <el-icon :size="16" color="#4caf50"><Picture /></el-icon>
                <span>识别结果图</span>
              </div>
            </template>
            <el-image
                :src="currentResultImage"
                fit="contain"
                class="result-image"
                :preview-src-list="[currentResultImage]"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
          </el-card>

          <!-- 信息区域 -->
          <el-card shadow="never" class="info-card">
            <template #header>
              <div class="section-header">
                <el-icon :size="16" color="#4caf50"><InfoFilled /></el-icon>
                <span>识别信息</span>
                <div class="result-switcher" v-if="selectedRecord.detection_details.length > 1">
                  <el-button
                      size="small"
                      :disabled="currentDetailIndex === 0"
                      @click="switchDetail(-1)"
                  >
                    <el-icon><ArrowLeft /></el-icon>
                  </el-button>
                  <span class="result-counter">
                    {{ currentDetailIndex + 1 }}/{{ selectedRecord.detection_details.length }}
                  </span>
                  <el-button
                      size="small"
                      :disabled="currentDetailIndex === selectedRecord.detection_details.length - 1"
                      @click="switchDetail(1)"
                  >
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>

            <div class="info-content">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="识别ID">{{ selectedRecord.detection_id }}</el-descriptions-item>
                <el-descriptions-item label="识别时间">{{ formatDate(selectedRecord.detection_time) }}</el-descriptions-item>
                <el-descriptions-item label="识别结果">
                  <el-tag :type="getTagType(currentDetail.result_value?.name)">
                    {{ currentDetail.result_value?.name || '未知' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="置信度">
                  <el-tag type="success">
                    {{ Math.round((currentDetail.confidence || 0) * 100) }}%
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="识别类型">
                  <el-tag :type="getTagType(selectedRecord.feature.feature_id)">
                    {{ selectedRecord.feature.feature_name }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
        </div>

        <!-- 建议区域 -->
        <el-card shadow="never" class="advice-card">
          <template #header>
            <div class="section-header">
              <el-icon :size="16" color="#4caf50"><Comment /></el-icon>
              <span>识别建议</span>
            </div>
          </template>

          <div class="advice-content">
            <el-card v-if="currentDetail.notes" shadow="never" class="advice-item">
              <div class="advice-content">{{ currentDetail.notes }}</div>
            </el-card>
            <el-empty v-else description="暂无相关建议" :image-size="80" />
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="showDetailModal = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 底部导航栏 -->
    <el-footer class="bottom-nav">
      <el-menu
          mode="horizontal"
          :default-active="activeIndex"
          class="nav-menu"
          @select="handleMenuSelect"
          active-text-color="#4caf50"
          :ellipsis="false"
      >
        <el-menu-item index="/home">
          <template #title>
            <el-icon :size="24"><HomeFilled /></el-icon>
            <span>首页</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/detection">
          <template #title>
            <el-icon :size="24"><Camera /></el-icon>
            <span>识别</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/gallery">
          <template #title>
            <el-icon :size="24"><Notebook /></el-icon>
            <span>图鉴</span>
          </template>
        </el-menu-item>
      </el-menu>
    </el-footer>
  </div>
</template>

<script>
import {
  Clock, ArrowLeft, ArrowRight, HomeFilled, Camera, Notebook,
  Picture, InfoFilled, Comment
} from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'HistoryPage',
  components: {
    Clock, ArrowLeft, ArrowRight, HomeFilled, Camera, Notebook,
    Picture, InfoFilled, Comment
  },
  data() {
    return {
      showDetailModal: false,
      selectedRecord: null,
      currentDetailIndex: 0,
      historyRecords: [],
      loading: false,
      activeIndex: '/history'
    }
  },
  computed: {
    currentDetail() {
      if (!this.selectedRecord) return {}
      return this.selectedRecord.detection_details[this.currentDetailIndex] || {}
    },
    currentResultImage() {
      if (!this.selectedRecord) return ''
      return this.processImage(this.selectedRecord.result_image)
    }
  },
  methods: {
    // 根据feature_id获取不同的标签类型
    getTagType(featureId) {
      const types = {
        1: 'primary',   // 种子质量
        2: 'success',   // 生长阶段
        3: 'warning',   // 叶片疾病
        4: 'danger'     // 果实成熟度
      }
      return types[featureId] || 'info'
    },
    formatDate(date) {
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    async fetchHistoryRecords() {
      this.loading = true
      try {
        const token = localStorage.getItem('token')
        if (!token) throw new Error('未登录')

        const userId = localStorage.getItem('userId')
        if (!userId) throw new Error('用户ID不存在')

        // 调用新的历史记录列表API
        const response = await axios.get('http://47.120.40.5:5000/api/detection/history/list', {
          headers: {
            'Authorization': `${token}`
          },
          params: { user_id: parseInt(userId) }
        })

        if (response.status !== 200) throw new Error(`请求失败: ${response.status}`)
        if (!response.data.success) throw new Error('获取数据失败')

        this.historyRecords = response.data.data
      } catch (err) {
        console.error('获取历史记录失败:', err)
        this.$message.error(err.message)
      } finally {
        this.loading = false
      }
    },
    async showDetails(record) {
      this.loading = true
      try {
        const token = localStorage.getItem('token')
        if (!token) throw new Error('未登录')

        // 调用详情API获取详细信息
        const response = await axios.get('http://47.120.40.5:5000/api/detection/history/detail', {
          headers: {
            'Authorization': `${token}`
          },
          params: { detection_id: record.detection_id }
        })

        if (response.status !== 200) throw new Error(`请求失败: ${response.status}`)
        if (!response.data.success) throw new Error('获取详情失败')

        this.selectedRecord = {
          ...response.data.data.detection_result,
          detection_details: response.data.data.detection_details
        }
        this.currentDetailIndex = 0
        this.showDetailModal = true
      } catch (err) {
        console.error('获取详情失败:', err)
        this.$message.error(err.message)
      } finally {
        this.loading = false
      }
    },
    processImage(image) {
      if (!image) return ''
      if (image.startsWith('data:image')) return image
      return `data:image/jpeg;base64,${image}`
    },
    goBack() {
      this.$router.back()
    },
    switchDetail(step) {
      const newIndex = this.currentDetailIndex + step
      if (newIndex >= 0 && newIndex < this.selectedRecord.detection_details.length) {
        this.currentDetailIndex = newIndex
      }
    },
    handleMenuSelect(index) {
      this.$router.push(index)
    },
    $isMobile() {
      return window.innerWidth < 768
    }
  },
  created() {
    this.fetchHistoryRecords()
  }
}
</script>
<style scoped>
/* 基础样式 */
.history-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8faf8;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.logo-image {
  height: 40px;
  border-radius: 40px;
}

.main-content {
  flex: 1;
  padding: 15px 15px 70px;
  overflow-y: auto;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.history-card {
  border-radius: 12px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.back-btn {
  position: absolute;
  right: 0;
  color: #4caf50;
}

/* 详情弹窗样式 */
.result-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-section {
  display: grid;
  grid-template-columns: 1.5fr 1fr;
  gap: 20px;
}

.image-card,
.info-card,
.advice-card {
  border-radius: 10px;
  margin-bottom: 20px;
}

.result-image {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #c0c4cc;
}

.info-content {
  padding: 10px;
}

/* 结果切换器 */
.result-switcher {
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-counter {
  font-size: 14px;
  color: #666;
}

/* 建议区域 */
.advice-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.advice-item {
  border-radius: 6px;
}

.advice-content {
  padding: 10px;
  color: #666;
  white-space: pre-line;
  line-height: 1.6;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0;
  height: 64px;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 1000;
}

.nav-menu {
  display: flex;
  justify-content: space-around;
  border: none;
  height: 100%;
}

.nav-menu :deep(.el-menu-item) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 64px;
  padding: 0;
  border-bottom: none;
  transition: all 0.3s;
}

.nav-menu :deep(.el-menu-item.is-active) {
  color: #4caf50 !important;
  background-color: #e8f5e9 !important;
}

.nav-menu :deep(.el-menu-item .el-icon) {
  margin-right: 0;
  margin-bottom: 6px;
  font-size: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px 10px 70px;
  }

  :deep(.el-table .cell) {
    white-space: nowrap;
    font-size: 14px;
  }

  .main-section {
    grid-template-columns: 1fr;
  }

  .result-image {
    height: 300px;
  }

  :deep(.el-dialog) {
    margin: 10px !important;
    width: calc(100% - 20px) !important;
  }

  .result-switcher {
    position: static;
    margin-left: auto;
  }
}
</style>